<template>
  <div class="music-box">
    <img src="@/assets/image/music.png" alt="null" title="点击静音" :style="{animationPlayState: state}" @click="zant">
    <audio :src="musicUrl" @ended="play()"></audio>
  </div>
</template>

<script>
export default {
  name: 'MyblogMusic',

  data() {
    return {
      state: 'paused', // 音频当前状态
      musicList: ['bgmusic.mp3','bgmusic-qyqx.mp3','bgmusic-ybxyq.mp3'], // 音频数据集
      musicUrl: require('@/assets/music/bgmusic.mp3'), // 当前播放的音频
      index: 0 // 随机索引
    };
  },

  methods: {
    zant() {
      this.state = this.state == 'running' ? 'paused' : 'running' ;
      let audio = document.getElementsByTagName('audio')[0];
      let i = parseInt(Math.random()*3);
      if(audio.paused){
        while(this.index == i)
          i = parseInt(Math.random()*3);
        this.index = i;
        this.musicUrl = require('@/assets/music/' + this.musicList[this.index]);
        setTimeout(()=>{
          audio.volume = 0.5;
          audio.play();
        },300);
      }else{
        audio.pause();
      }
    },
    play() {
      this.state = 'paused';
      setTimeout(()=>{
        this.zant();
      },1000);
    }
  },
};
</script>

<style scoped>
.music-box{
  width: 120px;
  height: 50px;
  background-color: white;
  position: fixed;
  top: 100px;
  left: -90px;
  border-radius: 40px;
  text-align: right;
  padding: 3px 10px;
  transition: all .3s;
}
.music-box:hover{
  left: -60px;
}
.music-box img{
  width: 44px;
  height: 44px;
  border-radius: 50%;
  transform-origin: center center;
  animation: rote 3s linear infinite;
}
@keyframes rote{
  from{
    transform: rotate(0deg);
  }
  to{
    transform: rotate(360deg);
  }
}
</style>